package com.csaba.swing.action;

import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.swing.AbstractAction;
import javax.swing.JOptionPane;
import javax.swing.KeyStroke;

import com.csaba.swing.MainWindow;
import com.csaba.swing.gui.GUIContext;
import com.csaba.swing.gui.util.GUIUtil;
import com.csaba.swing.model.Config;
import com.csaba.util.LoggerHelper;

@SuppressWarnings( "serial" )
public class ExitAction extends AbstractAction
{
	private final static Logger logger = LoggerHelper.getDefaultLogger();

	public ExitAction()
	{
		super(MainWindow.getString("ExitAction.menuItem")); //$NON-NLS-1$
		setEnabled(true);
		putValue(SMALL_ICON, GUIContext.getIcon("exit", 16)); //$NON-NLS-1$
		putValue(LARGE_ICON_KEY, GUIContext.getIcon("exit", 32)); //$NON-NLS-1$
		GUIUtil.setMnemonic(this);
		putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_X, ActionEvent.ALT_MASK));
	}

	@Override
	public void actionPerformed( final ActionEvent e )
	{
		if ( GUIContext.getInstance().hasActiveSession() )
		{
			final int result = JOptionPane.showConfirmDialog(MainWindow.getFrame(), MainWindow
					.getString("ExitAction.msg.closeSession"), MainWindow.getString("ExitAction.titleWarning"), //$NON-NLS-1$ //$NON-NLS-2$
					JOptionPane.OK_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE);
			if ( result == JOptionPane.CANCEL_OPTION )
			{
				return;
			}
			ActionFactory.getAction(LogoutAction.class).actionPerformed(null);
		}
		try
		{
			Config.saveConfig();
		}
		catch ( final IOException ex )
		{
			logger.log(Level.SEVERE, "Error during saving the config file", ex); //$NON-NLS-1$
		}
		MainWindow.getFrame().dispose();
	}

}
